package com.x9space.framework.elastic.handler;

import com.x9space.common.utils.StringUtils;
import com.x9space.framework.elastic.annotation.MultiMatch;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;

import java.lang.annotation.Annotation;
import java.util.Map;


public class MultiMatchQueryHandler extends QueryHandler{

    @Override
    public String getName() {

        return "MultiMatch";
    }

    @Override
    protected QueryBuilder _doHandle(Annotation annotation, Map<String,Object> context) {
        Object value = context.get("value");
        if (!(annotation instanceof MultiMatch)){
            return null;
        }

        MultiMatch item  = (MultiMatch)annotation;

        String[] fields = item.fields();
        if (fields==null || fields.length==0){
            return null;
        }
        MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery(value, fields);
        multiMatchQueryBuilder.minimumShouldMatch(item.minimumShouldMatch());
        if (!StringUtils.isEmpty(item.analyzer())){
            multiMatchQueryBuilder.analyzer(item.analyzer());
        }
        MultiMatchQueryBuilder.Type type = item.type();
        multiMatchQueryBuilder.type(type);
        switch (type){
            case BEST_FIELDS:
                multiMatchQueryBuilder.tieBreaker(item.tieBreaker());
                break;
            case CROSS_FIELDS:
                multiMatchQueryBuilder.operator(item.operator());
                break;
        }
        return multiMatchQueryBuilder;
    }
}
